﻿using Business.BookManagement.Dto;
using Business.Models;
using Business.Permissions;
using Business.WarehouseManagement.Dto;
using Microsoft.AspNetCore.Authorization;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection.Emit;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.ObjectMapping;
using XCZ;
using Yitter.IdGenerator;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;

namespace Business.WarehouseManagement
{
    [Authorize(BusinessPermissions.Warehouse.Default)]
    public class WarehouseAppService : BusinessWorkFlowAppService, IWarehouseAppService
    {
        private const string FormName = "Warehouse";
        private IRepository<Warehouse, Guid> _repository;
        private IRepository<Area, Guid> _areaRepository;
        private IRepository<WarehouseArea, Guid> _warehouseAreaRepository;

        public WarehouseAppService(IRepository<Warehouse, Guid> repository, IRepository<Area, Guid> areaRepository, IRepository<WarehouseArea, Guid> warehouseAreaRepository)
        {
            _repository = repository;
            _areaRepository = areaRepository;
            _warehouseAreaRepository = warehouseAreaRepository;
        }

        #region 增删改查基础方法


        //测试11111111111111
        public async Task<WarehouseDto> Get(Guid id)
        {
            var data = await _repository.GetAsync(id);
            var dto = ObjectMapper.Map<Warehouse, WarehouseDto>(data);
            return dto;
        }

        public async Task<List<WarehouseDto>> GetList()
        {
            var data = await _repository.GetListAsync();
            var dtos = ObjectMapper.Map<List<Warehouse>, List<WarehouseDto>>(data);
            return new List<WarehouseDto>(dtos);
        }

        public async Task<PagedResultDto<WarehouseDto>> GetAll(GetWarehouseInputDto input)
        {
            //var query = (await _repository.GetQueryableAsync()).WhereIf(string.IsNullOrWhiteSpace(input.WarehouseNo), a => a.WarehouseNo.Contains(input.WarehouseNo)).WhereIf(!string.IsNullOrWhiteSpace(input.WarehouseName), a => a.WarehouseName.Contains(input.WarehouseName)).WhereIf(input.WarehouseType > 0, a => a.WarehouseType == input.WarehouseType).WhereIf(input.DepartmentId > 0, a => a.DepartmentId == input.DepartmentId);
            var query = (await _repository.GetQueryableAsync()).WhereIf(!string.IsNullOrWhiteSpace(input.Filter), a => a.WarehouseName.Contains(input.Filter));

            var totalCount = await query.CountAsync();
            var items = await query.OrderByDescending(x => x.Id)
                        .ToListAsync();
            
            var dtos = ObjectMapper.Map<List<Warehouse>, List<WarehouseDto>>(items);
            return new PagedResultDto<WarehouseDto>(totalCount, dtos);
        }

        public async Task<WarehouseDto> CreateOrUpdate(CreateOrUpdateWarehouseDto input)
        {
            #region 校验

            //重名校验
            var warehouse = await _repository.FirstOrDefaultAsync(x => x.WarehouseName == input.WarehouseName && x.Id != input.Id);
            if (warehouse != null)
            {
                throw new BusinessException("仓库名称:" + input.WarehouseName + " 已存在!");
            }
            //重编号校验
            //warehouse = await _repository.FirstOrDefaultAsync(x => x.WarehouseNo == input.WarehouseNo && x.Id != input.Id);
            //if (warehouse != null)
            //{
            //    throw new BusinessException("仓库编号:" + input.WarehouseNo + " 已存在!");
            //}
            #endregion

            Warehouse result = null;
            if (!input.Id.HasValue)
            {

                input.Id = GuidGenerator.Create();
                
                result = await _repository.InsertAsync(ObjectMapper.Map<CreateOrUpdateWarehouseDto, Warehouse>(input));

                ////创建工作流
                //await WorkFlow.CreateWorkFlow(FormName, result);
                ////创建工作流
                //await WorkFlow.CreateWorkFlow(FormName, result);
                //创建工作流
                //await WorkFlow.CreateWorkFlow(FormName, result);
                ////创建工作流
                //await WorkFlow.CreateWorkFlow(FormName, result);
            }
            else
            {
                var data = await _repository.GetAsync(input.Id.Value);
                result = await _repository.UpdateAsync(ObjectMapper.Map(input, data));
                ////检查流程状态
                //await WorkFlow.CheckFormStatus(input.Id.Value, result);
                ////检查流程状态
                //await WorkFlow.CheckFormStatus(input.Id.Value, result);
                //检查流程状态
                //await WorkFlow.CheckFormStatus(input.Id.Value, result);
                ////检查流程状态
                //await WorkFlow.CheckFormStatus(input.Id.Value, result);
            }
            return ObjectMapper.Map<Warehouse, WarehouseDto>(result);
        }

        public async Task Delete(List<Guid> ids)
        {
            foreach (var item in ids)
            {
                await _repository.DeleteAsync(item);
            }
        }

        public async Task<TreeTypeDto> GetTreeType()
        {
            var warehouseList = await _repository.GetListAsync();
            var warehouseAreas = await _warehouseAreaRepository.GetListAsync();
            var areaList = await _areaRepository.GetListAsync();

            //返回树型结构
            var treeList = (from a in warehouseList
                            select new TreeNode
                            {
                                grade = "[仓库]",
                                code= a.WarehouseNo,
                                label = "[仓库] "+ a.WarehouseName,
                                id = a.Id.ToString().ToUpper(),
                                pid = "0",
                                children = (from b in areaList
                                            where b.PCode.ToUpper() == a.Id.ToString().ToUpper()
                                            select new TreeNode
                                            {
                                                grade = "[区域]",
                                                code = b.Code,
                                                label = "[区域] "+b.Name,
                                                id = b.Id.ToString().ToUpper(),
                                                pid = b.PCode.ToString().ToUpper(),
                                                children = (from c in warehouseAreas
                                                            where c.PCode.ToUpper() == b.Id.ToString().ToUpper()
                                                            select new TreeNode
                                                            {
                                                                grade = "[库区]",
                                                                code = c.Code,  
                                                                label = "[库区] "+c.Name,
                                                                id = c.Id.ToString().ToUpper(),
                                                                pid = c.PCode.ToString().ToUpper(),
                                                            }).ToList()
                                            }).ToList()


                            }).ToList();
            var totalCount = 0;
            var items = treeList;
            return new TreeTypeDto { totalCount=totalCount,items=items};

        }


        public async Task<List<WarehouseDto>> GetNewAll()
        {
            var query = await _repository.GetListAsync();

            var dto = ObjectMapper.Map<List<Warehouse>, List<WarehouseDto>>(query);
            return dto;
        }


        #endregion
    }
}
